<template>
  <div class="app-container">
    <!-- 天气展示区域-->
    <div class="weather-container mb8">
      <el-card class="weather-card" shadow="hover">
        <div class="weather-header">
          <div style="display: flex; align-items: center;">
            <el-icon class="weather-icon" style="color: #409EFF;">&#xe685;</el-icon>
            <span class="weather-title">实时天气</span>
          </div>

          <!-- 城市输入框 -->
          <el-input

            v-model="cityInput"
            placeholder="输入城市名"
            size="mini"
            style="width: 120px; margin-right: 10px;"
            @keyup.enter.native="handleCityChange(cityInput)"
          />

          <el-button
            type="text"
            size="mini"
            class="refresh-btn"
            @click="getWeather(cityInput || '郑州')"
            :loading="weatherLoading"
          >
            <el-icon v-if="!weatherLoading" class="refresh-icon">&#xe62f;</el-icon>
            <el-icon v-else class="el-icon-loading"></el-icon>
            查询
          </el-button>
        </div>


        <!-- 天气加载成功 -->
        <div v-if="weatherData && !weatherError" class="weather-content">
          <el-row :gutter="20" align="middle">
            <!-- 天气状况文字 -->
            <el-col :span="6" class="weather-text-col">
              <div class="weather-status" :class="weatherStatusClass">
                {{ weatherData.weather }}
              </div>
            </el-col>

            <!-- 核心天气信息 -->
            <el-col :span="12" class="weather-info-col">
              <div class="city-name fade-in">{{ weatherData.city }}</div>
              <div class="temperature">
                <span class="temp-value pulse">{{ weatherData.temp }}</span>
                <span class="temp-unit">℃</span>
              </div>
              <!-- 场景化提示语 -->
              <div class="weather-tip slide-up">{{ getWeatherTip() }}</div>
            </el-col>

            <!-- 更新时间（滚动效果） -->
            <el-col :span="6" class="weather-extra-col">
              <div class="update-time scroll-in">
                更新于: {{ weatherData.updateTime }}
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 天气加载失败（抖动提示） -->
        <div v-if="weatherError && !weatherLoading" class="weather-error shake">
          <el-icon style="color: #F56C6C;">&#xe626;</el-icon>
          <span>{{ weatherError }}</span>
          <el-button type="text" size="mini" @click="getWeather(cityInput || '郑州')">重试</el-button>
        </div>
      </el-card>
    </div>

    <!-- 公告列表部分（保持原有功能不变） -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input
          v-model="queryParams.noticeTitle"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作人员" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入操作人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="noticeType">
        <el-select v-model="queryParams.noticeType" placeholder="公告类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_notice_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:notice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:notice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:notice:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="noticeId" width="100" />
      <el-table-column
        label="公告标题"
        align="center"
        prop="noticeTitle"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="公告类型" align="center" prop="noticeType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_notice_type" :value="scope.row.noticeType"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_notice_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleView(scope.row)"
            v-hasPermi="['system:notice:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:notice:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:notice:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="公告标题" prop="noticeTitle">
              <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告类型" prop="noticeType">
              <el-select v-model="form.noticeType" placeholder="请选择公告类型">
                <el-option
                  v-for="dict in dict.type.sys_notice_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_notice_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容">
              <editor v-model="form.noticeContent" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看公告对话框 -->
    <el-dialog :title="title" :visible.sync="openView" width="780px" append-to-body>
      <el-descriptions column="2" border>
        <el-descriptions-item label="公告标题">{{ form.noticeTitle }}</el-descriptions-item>
        <el-descriptions-item label="公告类型">
          <dict-tag :options="dict.type.sys_notice_type" :value="form.noticeType"/>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="dict.type.sys_notice_status" :value="form.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="创建者">{{ form.createBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
      </el-descriptions>
      <el-divider>内容</el-divider>
      <div v-html="form.noticeContent"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNotice, getNotice, delNotice, addNotice, updateNotice } from "@/api/kobe/notice/notice"
import axios from 'axios' // 引入原生axios

export default {
  name: "Notice",
  dicts: ['sys_notice_status', 'sys_notice_type'],
  data() {
    return {
      cityInput: "",
      // 天气相关变量
      weatherData: null, // 存储天气数据
      weatherLoading: false, // 天气加载状态
      weatherError: "", // 天气错误信息
      apiKey: "SGM9UqPBGERjS2vPB", // 有效的API密钥
      openView: false,
      // 公告列表相关变量
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      noticeList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: undefined,
        createBy: undefined,
        status: undefined
      },
      form: {},
      rules: {
        noticeTitle: [
          { required: true, message: "公告标题不能为空", trigger: "blur" }
        ],
        noticeType: [
          { required: true, message: "公告类型不能为空", trigger: "change" }
        ]
      }
    }
  },
  computed: {
    // 根据天气状态生成对应的样式类（修正：移至computed选项内）
    weatherStatusClass() {
      const weather = this.weatherData?.weather || '';
      if (weather.includes('晴')) return 'sunny';
      if (weather.includes('雨')) return 'rainy';
      if (weather.includes('阴')) return 'cloudy';
      if (weather.includes('雪')) return 'snowy';
      if (weather.includes('霾') || weather.includes('雾')) return 'haze';
      return '';
    }
  },
  created() {
    this.getList() // 加载公告列表
    this.getWeather("郑州") // 初始加载郑州天气
  },
  methods: {
    /** 根据天气状况生成场景化提示语 */
    getWeatherTip() {
      if (!this.weatherData) return '';
      const { weather, temp } = this.weatherData;
      const tempNum = Number(temp);

      // 晴好天气
      if (weather.includes('晴')) {
        return tempNum > 25
          ? '☀️ 天气晴好，注意防晒，记得多喝水哦~'
          : '☀️ 阳光明媚，适合外出活动，体感舒适';
      }

      // 阴雨天气
      if (weather.includes('雨')) {
        return '🌧️ 记得带伞，路面湿滑，出行注意安全';
      }

      // 雾霾天气
      if (weather.includes('霾') || weather.includes('雾')) {
        return '😷 空气质量不佳，建议减少外出，佩戴口罩';
      }

      // 寒冷天气
      if (tempNum < 10) {
        return '❄️ 气温较低，注意添衣保暖，预防感冒';
      }

      // 一般天气
      return '🍃 天气适宜，愿你有美好的一天';
    },

    /** 获取实时天气数据（最终稳定版，用原生axios） */
    getWeather(city = "郑州") {
      this.weatherLoading = true;
      this.weatherError = "";
      const apiUrl = `/weather-proxy/v3/weather/now.json`;

      axios({
        url: apiUrl,
        method: "get",
        baseURL: "", // 去掉/dev-api前缀
        params: {
          key: this.apiKey,
          location: city,
          language: "zh-Hans",
          unit: "c"
        }
      })
        .then(response => {
          console.log("原生axios响应：", response);

          // 确保响应数据存在
          if (!response || !response.data) {
            this.weatherError = "响应数据为空";
            return;
          }

          const data = response.data;
          console.log("解析后的天气数据：", data);

          // 验证results数组
          if (Array.isArray(data.results) && data.results.length > 0) {
            const result = data.results[0];
            this.weatherData = {
              city: result.location.name,
              weather: result.now.text,
              temp: result.now.temperature,
              updateTime: this.parseTime(new Date(result.last_update), "{y}-{m}-{d} {h}:{i}")
            };
            console.log("赋值后的weatherData：", this.weatherData);
          } else {
            this.weatherError = "未查询到该城市天气数据";
          }
        })
        .catch(error => {
          console.error("天气请求失败：", error);
          this.weatherError = "请正确输入有效城市";
        })
        .finally(() => {
          this.weatherLoading = false;
        });
    },

    /** 城市查询处理 */
    handleCityChange(city) {
      if (city.trim()) {
        this.getWeather(city.trim())
      } else {
        this.$modal.msgWarning("请输入国内有效城市名")
      }
    },

    /** 公告列表查询 */
    getList() {
      this.loading = true
      listNotice(this.queryParams).then(response => {
        this.noticeList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 公告相关方法（保持不变）
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeType: undefined,
        noticeContent: undefined,
        status: "0"
      }
      this.resetForm("form")
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.noticeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleView(row) {
      this.reset()
      getNotice(row.noticeId).then(response => {
        this.form = response.data
        this.openView = true
        this.title = "查看公告"
      })
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加公告"
    },
    handleUpdate(row) {
      this.reset()
      const noticeId = row.noticeId || this.ids
      getNotice(noticeId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改公告"
      })
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.noticeId !== undefined) {
            updateNotice(this.form).then(() => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addNotice(this.form).then(() => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    handleDelete(row) {
      const noticeIds = row.noticeId || this.ids
      this.$modal.confirm(`是否确认删除公告编号为"${noticeIds}"的数据项？`).then(() => {
        return delNotice(noticeIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
/* 天气部分样式优化 */
.weather-container {
  margin-bottom: 16px;
}

.weather-card {
  border: none;
  border-radius: 12px;
  background: linear-gradient(135deg, #f5fafe 0%, #e8f4f8 100%);
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.15);
  overflow: hidden;
  transition: all 0.3s ease;
}

.weather-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 30px rgba(64, 158, 255, 0.2);
}

.weather-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.5);
}

.weather-title {
  font-size: 16px;
  font-weight: 600;
  color: #1989fa;
  margin-left: 8px;
}

.refresh-btn {
  color: #409EFF;
  transition: all 0.3s;
}

.refresh-btn:hover {
  color: #66b1ff;
}

.refresh-icon {
  transition: transform 0.5s ease;
}

.refresh-btn:hover .refresh-icon {
  transform: rotate(180deg);
}

/* 加载状态动画 */
.weather-loading {
  height: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(64, 158, 255, 0.1);
  border-left-color: #409EFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

.loading-content {
  color: #909399;
  font-size: 14px;
  animation: pulse 2s infinite;
}

/* 天气内容区域动画 */
.weather-content {
  padding: 20px;
}

.weather-text-col {
  display: flex;
  justify-content: center;
  align-items: center;
}

.weather-status {
  font-size: 24px;
  font-weight: 600;
  transition: all 0.5s ease;
  padding: 8px 16px;
  border-radius: 20px;
}

/* 不同天气状态的样式 */
.weather-status.sunny {
  color: #ff9800;
  background-color: rgba(255, 152, 0, 0.1);
}

.weather-status.rainy {
  color: #2196f3;
  background-color: rgba(33, 150, 243, 0.1);
}

.weather-status.cloudy {
  color: #7b8794;
  background-color: rgba(123, 135, 148, 0.1);
}

.weather-status.snowy {
  color: #64b5f6;
  background-color: rgba(100, 181, 246, 0.1);
}

.weather-status.haze {
  color: #a0a0a0;
  background-color: rgba(160, 160, 160, 0.1);
}

.weather-info-col {
  text-align: left;
}

.city-name {
  font-size: 20px;
  font-weight: 700;
  color: #1d2129;
  margin-bottom: 4px;
}

.temperature {
  display: flex;
  align-items: baseline;
  margin: 8px 0;
}

.temp-value {
  font-size: 36px;
  font-weight: 700;
  color: #1989fa;
  line-height: 1;
}

/* 提示语样式 */
.weather-tip {
  font-size: 13px;
  padding: 6px 12px;
  border-radius: 4px;
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
  display: inline-block;
}

/* 额外信息 */
.weather-extra-col {
  text-align: right;
}

.update-time {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 错误提示 */
.weather-error {
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #F56C6C;
  font-size: 14px;
}

.weather-error el-button {
  margin-top: 8px;
  color: #409EFF;
  padding: 0;
}

/* 动画定义 */
@keyframes spin {
  to { transform: rotate(360deg); }
}

@keyframes pulse {
  0% { opacity: 0.7; }
  50% { opacity: 1; }
  100% { opacity: 0.7; }
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(10px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

@keyframes scrollIn {
  from { transform: translateX(20px); opacity: 0; }
  to { transform: translateX(0); opacity: 1; }
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  20% { transform: translateX(-5px); }
  40% { transform: translateX(5px); }
  60% { transform: translateX(-3px); }
  80% { transform: translateX(3px); }
}

/* 应用动画类 */
.fade-in {
  animation: fadeIn 0.6s ease forwards;
}

.slide-up {
  animation: slideUp 0.6s ease 0.2s forwards;
  opacity: 0;
}

.scroll-in {
  animation: scrollIn 0.6s ease 0.4s forwards;
  opacity: 0;
}

.pulse {
  animation: pulse 3s infinite;
}

.shake {
  animation: shake 0.5s ease;
}
</style>
